<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>layui</title>
    <!-- <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> -->
    <link rel="stylesheet" href="/lib/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <style>
        .layui-btn:not(.layui-btn-lg):not(.layui-btn-sm):not(.layui-btn-xs) {
            height: 34px;
            line-height: 34px;
            padding: 0 8px;
        }
    </style>
</head>

<body>
    <div class="layuimini-container">
        <div class="layuimini-main">
            <!-- <blockquote class="layui-elem-quote">
                Layui的树形表格treeTable，支持异步加载(懒加载)、复选框联动、折叠状态记忆。<br>
            </blockquote> -->
            <div>
                <div class="layui-btn-group">
                    <button class="layui-btn" id="btn-expand">全部展开</button>
                    <button class="layui-btn layui-btn-normal" id="btn-fold">全部折叠</button>
                </div>
                <div class="layui-btn-group">
                    <button class="layui-btn" id="btn-addUser">添加用户</button>
                </div>
                <table id="munu-table" class="layui-table" lay-filter="munu-table"></table>
            </div>


        </div>
    </div>

    <!-- 操作列 -->
    <script type="text/html" id="auth-state">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="editKong">修改占控</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="editUser">编辑</a>
        <a class="layui-btn layui-btn-xs" lay-event="adjustBalance">调整余额</a>
        <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="editRatio">修改比例</a>
        <!-- <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="userLog">日志</a> -->
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delUser">删除</a>
    </script>


    <script src="/lib/layui/layui.js" charset="utf-8"></script>
    <script src="/lib/axios/axios.js" charset="utf-8"></script>
    <script src="/js/lay-config.js" charset="utf-8"></script>
    <script>
        //layui官方的是treeTable,这里是第三方的,是treetable
        layui.use(['table', 'treetable'], function () {
            const $ = layui.jquery
            const table = layui.table
            let treeTable = layui.treetable;

            window.data = null
            let fistDoc = null
            const treeData = {
                treeColIndex: 1,
                treeSpid: -1,
                treeIdName: '_id',
                treePidName: 'parent',
                // rootPid: 'parent',
                // id: 'treeId', // 自定义 id 索引
                elem: '#munu-table',
                url: '/user/allUser',
                method: 'get',
                // toolbar: '#toolbarDemo',
                // defaultToolbar: ['filter', 'exports', 'print', {
                //     title: '提示',
                //     layEvent: 'LAYTABLE_TIPS',
                //     icon: 'layui-icon-tips'
                // }],
                cols: [[
                    { type: "checkbox", width: 50 },
                    { field: 'userName', minWidth: 100, title: '用户名', sort: true },
                    // { field: '_id', minWidth: 40, title: 'ID', sort: true },
                    { field: 'maxDeviceNum', width: 100, title: '可管理控数' },
                    { field: 'userDeviceNum', width: 100, title: '占用控数' },
                    { field: 'balance', width: 120, title: '余额(元)', templet: function(d){ return '¥' + ((d.balance || 0) / 100).toFixed(2); } },
                    { field: 'points', width: 120, title: '可用积分', templet: function(d){ return Math.floor(((d.balance || 0) / 100) * (d.pointsRatio || 10000)); } },
                    { field: 'pointsRatio', width: 120, title: '积分比例', templet: function(d){ return '1元=' + (d.pointsRatio || 10000) + '积分'; } },
                    // { field: 'checkStatus', width: 100, title: '账号状态' },
                    // { field: 'touPing', minWidth: 40, title: '投屏状态' },
                    { field: 'beiZhu', width: 100, title: '备注' },
                    // { title: '操作', width: 260, toolbar: '#currentTableBar', align: "center" },
                    { templet: '#auth-state', minWidth: 100, align: 'center', title: '操作' }
                ]],
                done: function (res, curr, count) {
                    // console.log(res, curr, count);
                    fistDoc = res.data[0]
                    // console.log(fistDoc, "fistDoc");
                    // layer.closeAll('loading');
                }
            }

            // layer.load(2);
            treeTable.render(treeData);

            $('#btn-expand').click(function () {
                treeTable.expandAll('#munu-table');
            });

            $('#btn-fold').click(function () {
                treeTable.foldAll('#munu-table');
            });

            $('#btn-addUser').click(function () {
                fistDoc.uiType = "添加用户"
                openUser(fistDoc)
            });


            //监听工具条
            table.on('tool(munu-table)', function (obj) {
                let data = obj.data;
                let layEvent = obj.event;

                if (data.parent == '-1' && layEvent != "editKong") {
                    layer.msg("顶级用户不支持编辑/删除");
                    return false
                }

                if (layEvent === 'delUser') {
                    layer.confirm(`真的要删除[${data.userName}]?`, function (index) {
                        axios.post('/user/delUser', { _id: data._id }).then(function (res) {
                            if (res.data.code == 0) {
                                layer.msg(res.data.msg);
                                layer.close(index);
                                location.reload();
                            } else {
                                layer.alert('删除失败:' + res.data.msg);
                            }
                        }).catch(function (err) {
                            console.log("删除错误", err);
                            layer.msg('删除错误' + err.message);
                        });
                    });
                } else if (layEvent === 'editUser') {
                    data.uiType = "编辑用户"
                    openUser(data)
                } else if (layEvent === "editKong") {
                    editKong(data)
                } else if (layEvent === 'adjustBalance') {
                    adjustBalance(data)
                } else if (layEvent === 'editRatio') {
                    editRatio(data)
                } else if (layEvent === 'userLog') {
                    openLog(data)
                } else if (layEvent === 'tou_Ping') {
                    touPing(data)
                }
            });

            function editKong(data) {
                layer.prompt({
                    formType: 2,
                    value: data.userDeviceNum,
                    title: '更改代理:【' + data.userName + "】的占用控数",
                    area: ['150px', '40px'] //自定义文本域宽高
                }, function (value, index, elem) {
                    layer.close(index);
                    if (data.userDeviceNum == value || !/^\d+$/.test(value)) {
                        layer.msg("未修改或无效输入")
                        return
                    }
                    if (Number(value) > data.maxDeviceNum) {
                        layer.msg(`本账号${data.userName}不足以开这么多控,最大${data.maxDeviceNum}`)
                        return false
                    }

                    axios.post('/user/editKong', {
                        _id: data._id,
                        userName: data.userName,
                        parentId: data.parent,
                        userDeviceNum: Number(value),
                        maxDeviceNum: data.maxDeviceNum
                    }).then(function (res) {
                        if (res.data.code == 0) {
                            layer.msg(res.data.msg);
                            layer.close(index);
                            location.reload();
                        } else {
                            layer.alert('修改占控失败:' + res.data.msg);
                        }
                    }).catch(function (err) {
                        console.log("修改占控错误", err);
                        layer.msg('修改占控错误' + err.message);
                    });
                });
            }

            function adjustBalance(data) {
                layer.open({
                    type: 1,
                    title: '调整用户【' + data.userName + '】的余额',
                    area: ['400px', '500px'],
                    content: `
                        <div style="padding: 20px;">
                            <div class="layui-form">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">当前余额</label>
                                    <div class="layui-input-block">
                                        <input type="text" value="¥${((data.balance || 0) / 100).toFixed(2)}" readonly class="layui-input layui-disabled">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">调整类型</label>
                                    <div class="layui-input-block">
                                        <select name="transactionType" lay-search>
                                            <option value="后台充值">后台充值</option>
                                            <option value="后台赠送">后台赠送</option>
                                            <option value="后台扣款">后台扣款</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">调整金额(元)</label>
                                    <div class="layui-input-block">
                                        <input type="number" id="adjustAmount" placeholder="请输入调整金额(元)" class="layui-input" step="0.01" min="0.01">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">调整原因</label>
                                    <div class="layui-input-block">
                                        <textarea id="adjustReason" placeholder="请输入调整原因" class="layui-textarea"></textarea>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <button class="layui-btn" onclick="submitAdjustBalance('${data._id}', '${data.userName}')">确认调整</button>
                                        <button class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `,
                    success: function() {
                        layui.form.render();
                    }
                });
            }

            function editRatio(data) {
                layer.prompt({
                    formType: 0,
                    value: data.pointsRatio || 10000,
                    title: '修改用户【' + data.userName + '】的积分比例',
                    area: ['300px', '150px']
                }, function(value, index) {
                    if (!/^\d+$/.test(value) || Number(value) <= 0) {
                        layer.msg('请输入有效的积分比例');
                        return;
                    }
                    
                    axios.post('/user/updatePointsRatio', {
                        targetUserId: data._id,
                        pointsRatio: Number(value)
                    }).then(function(res) {
                        if (res.data.code === 0) {
                            layer.msg('修改成功');
                            layer.close(index);
                            location.reload();
                        } else {
                            layer.msg(res.data.msg);
                        }
                    }).catch(function(err) {
                        layer.msg('修改失败: ' + err.message);
                    });
                });
            }

            function openUser(data) {
                // let title = "添加用户"
                // console.log("data", data);
                window.data = data
                let index = layer.open({
                    title: data.uiType,
                    type: 2,
                    anim: 4,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['70%', '60%'],
                    content: './addUser.html',
                    end: function () {
                        // console.log("编辑用户,重载表格", treeTable);
                        // treeTable.render(treeData);
                        window.data = null
                        location.reload();
                    }
                });
            }


            async function openLog(data) {
                const res = await axios.get('/user/userLog?userName=' + data.userName)
                const resdata = res.data
                if (resdata.code == 0) {
                    if (resdata.data.length == 0) {
                        layer.msg('暂无记录')
                        return
                    } else {
                        let content = ""
                        resdata.data.forEach(res => {
                            content = res.logTime + "->" + res.logStr + "<br><br>" + content
                        })
                        layer.open({
                            type: 1,
                            title: data.userName + "的日志",
                            // area: ['500px', '300px'],
                            shadeClose: true,
                            content: content
                        });
                    }
                } else {
                    layer.msg(resdata.msg)
                }
            }


            function touPing(data) {
                var index = layer.open({
                    title: "用户【" + data.userName + "】的设备管理",
                    type: 2,
                    anim: 4,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['95%', '95%'],
                    content: '/page/table/tableDevice.html',
                    btn: ["关闭"],
                    success: function (layero, index) {
                        // layer.msg("加载成功")
                        let iframeWin = $(layero).find('iframe')[0].contentWindow
                        iframeWin.chuanCan(data.userName)
                    },
                });
            }

        });

        // 全局函数：提交余额调整
        window.submitAdjustBalance = function submitAdjustBalance(userId, userName) {
            var transactionType = document.querySelector('select[name="transactionType"]').value;
            var amount = document.getElementById('adjustAmount').value;
            var reason = document.getElementById('adjustReason').value;
            
            if (!transactionType) {
                layer.msg('请选择调整类型');
                return;
            }
            
            if (!amount || parseFloat(amount) <= 0) {
                layer.msg('请输入有效的调整金额');
                return;
            }
            
            // 将元转换为分
            var amountInCents = Math.round(parseFloat(amount) * 100);
            
            if (!reason.trim()) {
                layer.msg('请输入调整原因');
                return;
            }
            
            // 根据操作类型确定金额正负
            var isPositive = ['后台充值', '后台赠送'].includes(transactionType);
            var finalAmountInCents = isPositive ? amountInCents : -amountInCents;
            
            axios.post('/user/adjustBalance', {
                userId: userId,
                amount: finalAmountInCents,
                transactionType: transactionType,
                description: reason
            }).then(function(res) {
                if (res.data.code === 0) {
                    layer.msg('调整成功');
                    layer.closeAll();
                    location.reload();
                } else {
                    layer.msg(res.data.msg);
                }
            }).catch(function(err) {
                layer.msg('调整失败: ' + err.message);
            });
        };
    </script>


</body>

</html>